import { Toast } from "@/utils";
import { defHttp } from "@/utils/http";
import { editFileName, getFileExtension } from "./utils";

export function useSaveFile() {

  /**
   * @description 下载文件
   * @date 14/11/2023
   * @param {string} filePath
   * @returns {*}  {Promise<string>}
   */
  async function downloadFile(filePath: string): Promise<string> {
    try {
      const res = await defHttp.download(filePath)
      return res
    } catch (error) {
      Toast('下载失败')
      return Promise.reject(error)
    }
  }

  async function saveImage(filePath: string, customFileName?: string) {
    const extension = getFileExtension(filePath)
    let tempFilePath = await downloadFile(filePath)
    if (customFileName) {
      tempFilePath = await editFileName(tempFilePath, customFileName, extension)
    }
    await uni.saveImageToPhotosAlbum({
      filePath: tempFilePath,
    })
    Toast('保存成功，请到手机相册查看')
  }

  return {
    saveImage,
    downloadFile
  }
}